<script setup lang="ts">
import { ref, type Ref, reactive } from "vue";
import { Search } from "@element-plus/icons-vue";
import type { VxeGridProps } from "vxe-table";
import { Close } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { getUserInfoApi, userDetailSaveApi } from "@/api/user";

import ChooseUserGroupDialog from "./ChooseUserGroupDialog.vue";

defineOptions({
  name: "BasicInfo"
});
const userInfo: Ref<Record<string, any>> = ref({});
const instanceId: Ref<string> = ref("");
const instanceDesc: Ref<string> = ref("");
const userGroupId: Ref<string> = ref("");

interface Row {
  userGroupId: string;
  instanceDesc: string;
}

const gridOptions = reactive<VxeGridProps<Row>>({
  height: "100%",
  columns: [
    {
      title: "User Group ID",
      field: "instanceId"
    },
    {
      title: "Description",
      field: "instanceDesc"
    },
    {
      title: "Action",
      width: 120,
      slots: { default: "action" }
    }
  ],
  data: [],
  stripe: true,
  rowConfig: { keyField: "userGroupId" }
});

const chooseUserGroupDialog = ref(null);

type IPage = {
  pageSize: number;
  total: number;
};

const page: Ref<IPage> = ref({
  pageSize: 10,
  total: gridOptions.data.length
});

// 查询User Info
const getUserInfo = () => {
  const form = new FormData();
  // form.append("lockVersion", "");
  // form.append("updateTimeCheck", "");
  // form.append("optimisticLockCheck", "");
  // form.append("accessToken", "R8/iY74etD3qQ5qbtw10IUehpd/6IakgmR/ACls=");
  form.append("instanceId", "ADMIN");
  form.append("namedSpace", "MYCIM2");
  // form.append("instanceDesc", "");
  // form.append("userName", "STRESS");
  // form.append("localName", "");
  // form.append("shiftId", "CP,IT");
  // form.append("userStatus", "NORMAL");
  // form.append("telMobile", "NORMAL");
  // form.append("emailAddress", "NORMAL");
  // form.append("telOffice", "NORMAL");
  // form.append("pagerNumber", "NORMAL");
  // form.append("sAdhoc", "MES-11978: Please re-enter Password to confirm it.");
  // form.append("newpassword", "●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●");
  // form.append("password", "8724aa758c2f662d79952870ef486ea6");
  // form.append("verifypassword", "●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●");
  // form.append("passwordConfirm", "8724aa758c2f662d79952870ef486ea6");
  // form.append("ldapId", "");
  getUserInfoApi(form).then((res: any) => {
    if (res.body) {
      userInfo.value = res.body.userprofile;
      instanceId.value = res.body.userprofile.instanceId;
      instanceDesc.value = res.body.userprofile.instanceDesc;
      gridOptions.data = res.body.userprofile.userGroups;
      page.value.total = gridOptions.data.length;
    }
  });
};

getUserInfo();

const handleDeleteUserGroup = row => {
  ElMessageBox.confirm("Are you sure?", "Warning", {
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
    type: "warning"
  }).then(async () => {
    const formData = new FormData();
    formData.append("lockVersion", "");
    formData.append("updateTimeCheck", "");
    formData.append("pages", "1");
    formData.append("instanceId", userInfo.value.instanceId);
    formData.append("namedSpace", userInfo.value.namedSpace);
    formData.append("instanceDesc", "");
    formData.append("userGroupId", "");
    await userDetailSaveApi({
      urlParams: {
        action: "delete",
        item: row.instanceRrn
      },
      formData
    });
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    // 删除之后重新查询数据
    getUserInfo();
  });
};

// 打开搜索
const handleSearch = () => {
  chooseUserGroupDialog.value.open(userGroupId.value);
};

// 关闭搜索的回调
const setUserGroupId = id => {
  userGroupId.value = id;
};

// 确认添加User Group
const handleAddUserGroup = async () => {
  const params: any = {
    urlParams: {
      action: "create",
      create: 1
    }
  };
  const formData = new FormData();
  formData.append("lockVersion", "");
  formData.append("updateTimeCheck", "");
  formData.append("pages", "1");
  formData.append("instanceId", userInfo.value.instanceId);
  formData.append("namedSpace", userInfo.value.namedSpace);
  formData.append("instanceDesc", "");
  formData.append("userGroupId", userGroupId.value);
  params.formData = formData;
  await userDetailSaveApi(params);
  ElMessage({
    message: "添加成功",
    type: "success"
  });
  // 添加之后重新查询数据
  getUserInfo();
};

// Cancel
const handleCancel = () => {
  console.log("cancel");
};
</script>

<template>
  <div class="basic-info">
    <el-form label-width="120" label-position="left">
      <el-form-item label="User ID">
        <el-input v-model="instanceId" disabled />
      </el-form-item>
      <el-form-item label="Description">
        <el-input v-model="instanceDesc" type="textarea" :rows="1" disabled />
      </el-form-item>
    </el-form>
    <div class="field-set">
      <span class="title">User Group List</span>
      <div class="field-list">
        <vxe-grid v-bind="gridOptions">
          <template #action="{ row }">
            <div class="action">
              <el-icon
                size="22"
                color="red"
                @click="handleDeleteUserGroup(row)"
              >
                <Close />
              </el-icon>
            </div>
          </template>
        </vxe-grid>
      </div>
    </div>

    <el-form class="add-group" label-width="120" label-position="left">
      <el-form-item label="User Group ID">
        <el-input v-model="userGroupId" style="width: 200px" />
        <el-button class="search-icon" :icon="Search" @click="handleSearch" />
        <el-button type="primary" @click="handleAddUserGroup">
          Add User Group
        </el-button>
        <vxe-pager
          v-model:page-size="page.pageSize"
          :total="page.total"
          :layouts="['PrevJump', 'PrevPage', 'NextPage', 'NextJump']"
        />
      </el-form-item>
    </el-form>
    <div class="page-operation">
      <el-button type="primary" @click="handleCancel">Cancel</el-button>
    </div>
    <ChooseUserGroupDialog
      ref="chooseUserGroupDialog"
      @cell-click="setUserGroupId"
    />
  </div>
</template>

<style lang="scss" scoped>
.basic-info {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-form-item) {
  .el-form-item__label {
    font-size: 16px;
    font-weight: normal;
    color: #000000;
  }
}

.field-set {
  flex: 1;
  display: flex;
  position: relative;
  border: solid 1px #000;
  min-height: 100px;
  padding: 16px 22px;
  gap: 36px;
  margin-top: 24px;

  .title {
    position: absolute;
    display: inline-block;
    top: -12px;
    left: 10px;
    font-family: "微软雅黑", sans-serif !important;
    font-size: 16px;
    font-weight: bold;
    color: Black;
    background: #fff;
    font-style: italic;
    padding: 0 10px;
  }

  .field-list {
    flex: 1;
    overflow: hidden;

    :deep(.vxe-grid) {
      .vxe-cell--title,
      .vxe-cell--label {
        font-size: 16px;
        font-weight: normal;
        color: #000000;
      }
    }

    .action {
      display: flex;
      align-items: center;

      .el-icon {
        cursor: pointer;
      }
    }
  }
}

.vxe-pager {
  margin-left: auto;
  --vxe-table-row-height-medium: 32px;
}

.add-group {
  margin-top: 6px;

  .search-icon {
    margin-left: 12px;
    font-weight: 900;
    color: var(--el-color-primary);
  }
}

.page-operation {
  display: flex;
  justify-content: center;
  margin-bottom: 36px;
}
</style>
